package com.itzb.asone.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itzb.asone.application.BaseController;
import com.itzb.asone.constant.SystemConstant;
import com.itzb.asone.constant.SystemMessageConstant;
import com.itzb.asone.constant.model.SysUserConstant;
import com.itzb.asone.mybatis.Criteria;
import com.itzb.asone.system.model.SysUser;
import com.itzb.asone.system.service.IMessageService;
import com.itzb.asone.system.service.ISysUserService;
import com.itzb.asone.utils.CipherUtil;
import com.itzb.asone.utils.JsonResult;

@Controller
@RequestMapping(value = "")
public class LoginController extends BaseController {
	
	private Logger logger = Logger.getLogger(getClass()); 
	
	@Autowired
	private IMessageService messageService;
	@Autowired
	private ISysUserService sysUserService;

	@RequestMapping(value = "system/login", method = { RequestMethod.GET })
	public String login(ModelMap map, HttpServletRequest request,HttpServletResponse response) {
		return "login";
	}
	
	@ResponseBody
	@RequestMapping(value = "system/userLogin", method = { RequestMethod.POST })
	public JsonResult userLogin(ModelMap map, HttpServletRequest request,HttpServletResponse response) {
		JsonResult jsonResult = JsonResult.newInstance();
		Criteria<SysUser> param = new Criteria<SysUser>();
		List<SysUser> list = new ArrayList<SysUser>();
		String userName = request.getParameter("userName").trim();
		String passWord = request.getParameter("password");
		
		SysUser sysUser = sysUserService.queryEntityByUserName(userName);
		//校验该用户名是否存在
		if(sysUser == null){
			param.clearParams();
			param.addParam("tel", userName);
			list = sysUserService.queryPage(param);
			if(list != null && list.size() > 0){
				sysUser = list.get(0);
			}
		}
		if(sysUser == null){
			param.clearParams();
			param.addParam("email", userName);
			list = sysUserService.queryPage(param);
			if(list != null && list.size() > 0){
				sysUser = list.get(0);
			}
		}
		if(sysUser == null){
			jsonResult.declareFailure(messageService.message(SystemMessageConstant.SYSTEM_LOGIN_ERROR_01));
			return jsonResult;
		}
		//校验用户状态
		if(sysUser.getStatus().equals(SysUserConstant.T_SYS_USER_STATUS_0)){
			jsonResult.declareFailure(messageService.message(SystemMessageConstant.SYSTEM_LOGIN_ERROR_04));
			return jsonResult;
		}
		if(sysUser.getStatus().equals(SysUserConstant.T_SYS_USER_STATUS_3)){
			jsonResult.declareFailure(messageService.message(SystemMessageConstant.SYSTEM_LOGIN_ERROR_03));
			return jsonResult;
		}
		//校验用户密码
		if(!CipherUtil.validatePassword(sysUser.getUserName(),sysUser.getPassword() , passWord)){
			sysUserService.addPasswordRepTimes(sysUser.getId());
			jsonResult.declareFailure(messageService.message(SystemMessageConstant.SYSTEM_LOGIN_ERROR_02));
			return jsonResult;
		}
		//登录成功
		//密码错误测试更新为0
		param.clearParams();
		sysUser.setPasswordRepTimes(0);
		param.setRecord(sysUser);
		param.addParam("id", sysUser.getId());
		sysUserService.updateByCriteria(param);
		response = this.setCookie(sysUser, response);
		jsonResult.declareSuccess();
	    jsonResult.addContent("redirect", "/system/main");


		return jsonResult;
	}
	
	@RequestMapping(value = "system/logout", method = { RequestMethod.GET })
	public String logout(HttpServletRequest request,HttpServletResponse response) {
		Cookie cookie = new Cookie(SystemConstant.USER_COOKIE_NAME, null);
		cookie.setMaxAge(0);
		cookie.setPath("/");
		response.addCookie(cookie);
		
		request.getSession(true).removeAttribute(SystemConstant.USER_RESOURCE);
		request.getSession(true).removeAttribute(SystemConstant.USER_INFO);
		
		return "login";
	}
	
	@RequestMapping(value = "system/main", method = { RequestMethod.GET })
	public String loginMain(ModelMap map) {
		return "pagelet/main";
	}

	@RequestMapping(value = "", method = { RequestMethod.GET })
	public String main(ModelMap map) {
		return "pagelet/main";
	}
	
	
	
	
	
	private HttpServletResponse setCookie(SysUser sysUser,HttpServletResponse response){
		String userCookieName = sysUser.getId() + "_" + sysUser.getUserName();
		Cookie cookie = new Cookie(SystemConstant.USER_COOKIE_NAME, userCookieName);
		cookie.setPath("/");
		cookie.setMaxAge(-1); 	//	设置cook过期时间为: 关闭浏览器后过期
		response.addCookie(cookie);
		return response;
	}
}
